package Socket;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * 聊天室客户端
 */
public class Client_1 {
    /*
        java.net.Socket "套接字"
        该类封装了TCP协议的通讯细节，使用它可以与服务端建立连接，并基于
        两条流(输入与输出)的读写完成与对方的交互。
        我们可以将Socket比喻为"电话"。
     */
    private Socket socket;
    /*
        windows
        win+r :输入cmd回车
        在命令行中输入ipconfig查看自己的IP地址

        mac
        五个指头在触摸板上向中间抓，找到"终端"这个软件并打开
        在终端程序中输入ifconfig查看自己的IP地址

     */
    public Client_1(){
        try {
            /*
                实例化Socket时就是与远端计算机建立连接的过程。
                这里需要传入两个参数:
                1:服务端的IP地址，用于找到网络上对方的计算机
                2:服务端口，用于找到服务端计算机上的服务端应用程序
             */
            System.out.println("正在连接服务端...");
            socket = new Socket("176.225.131.2",8088);
            System.out.println("与服务端建立连接!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start(){
        Thread read = new Thread(new Read(socket));
        Thread received =new Thread(new Received(socket));

        read.setDaemon(true);
        read.start();
        received.start();
    }

    public static void main(String[] args) {
        Client_1 client = new Client_1();
        client.start();
    }

}

class Read implements Runnable{
    private Socket socket;
    public Read(Socket socket) {
        this.socket = socket;
    }
    @Override
    public void run() {
        try {
            InputStream in = socket.getInputStream();
            InputStreamReader isr = new InputStreamReader(in,StandardCharsets.UTF_8);
            BufferedReader br = new BufferedReader(isr);

            String received;
            while ((received = br.readLine())!=null){
                System.out.println("客户端说:"+received);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

class Received implements Runnable{

    private Socket socket;
    public Received(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            OutputStream out = socket.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(out, StandardCharsets.UTF_8);
            BufferedWriter bw = new BufferedWriter(osw);
            PrintWriter pw = new PrintWriter(bw,true);

            Scanner sc = new Scanner(System.in);

            String send;
            while (true){
                send = sc.nextLine();
                if("exit".equals(send)){
                    break;
                }
                pw.println(send);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
